<template>
  <div class="flex flex-col h-full">
    <!-- Chat Message Area -->
    <div class="flex-1 overflow-y-auto p-4 bg-gray-50" ref="messageContainer">
      <!-- Messages List -->
      <div v-for="(message, index) in messages" :key="message.id" class="mb-6">
        <!-- AI/System Message -->
        <template v-if="message.type === 'system'">
          <div class="flex items-start mb-2">
            <div class="w-10 h-10 rounded-md bg-blue-100 flex items-center justify-center mr-3 flex-shrink-0">
              <i class="fas fa-robot text-blue-500"></i>
            </div>
            <div class="bg-white rounded-lg p-3 shadow-sm max-w-3xl">
              <div class="flex items-center mb-1">
                <h3 class="text-base font-medium text-gray-900">{{ message.sender }}</h3>
                <button v-if="message.collapsible" class="ml-auto text-gray-500 text-sm">
                  {{ message.collapsed ? '展开 ∨' : '收起 ^' }}
                </button>
              </div>
              <div v-if="!message.collapsed" class="text-sm text-gray-700 space-y-2">
                <template v-if="Array.isArray(message.content)">
                  <p v-for="(item, itemIndex) in message.content" :key="itemIndex" 
                     :class="{ 'flex items-start': item.icon, 'mt-3': item.type === 'text' }">
                    <span v-if="item.icon" :class="getIconClass(item.icon)" class="mr-2">{{ item.icon }}</span>
                    <span>{{ item.text }}</span>
                  </p>
                </template>
                <p v-else>{{ message.content }}</p>
              </div>
            </div>
          </div>

          <div v-if="message.meta" class="flex items-center mb-3 text-xs text-gray-500 pl-14">
            <span class="mr-2">👉 {{ message.meta }}</span>
            <span class="ml-auto">{{ message.time }}</span>
          </div>
        </template>

        <!-- User Message -->
        <template v-else-if="message.type === 'user'">
          <div class="flex justify-end mb-1">
            <div class="mr-3 flex flex-col items-end">
              <div class="bg-indigo-600 text-white rounded-lg p-3 max-w-xl">
                <p class="text-sm">{{ message.content }}</p>
              </div>
              <span class="text-xs text-gray-500 mt-1">{{ message.sender }}</span>
            </div>
            <div class="w-10 h-10 rounded-full overflow-hidden flex-shrink-0">
              <img :src="getUserAvatar(message.sender)" alt="User" class="w-full h-full object-cover">
            </div>
          </div>
        </template>
      </div>

      <!-- Loading Indicator -->
      <div v-if="isTyping" class="flex items-start mb-2">
        <div class="w-10 h-10 rounded-md bg-blue-100 flex items-center justify-center mr-3 flex-shrink-0">
          <i class="fas fa-robot text-blue-500"></i>
        </div>
        <div class="bg-white rounded-lg p-3 shadow-sm">
          <div class="flex space-x-1">
            <div class="typing-dot"></div>
            <div class="typing-dot animation-delay-200"></div>
            <div class="typing-dot animation-delay-400"></div>
          </div>
        </div>
      </div>
    </div>

    <!-- Message Input Area -->
    <div class="border-t border-gray-200 p-4 bg-white">
      <div class="flex items-center mb-3">
        <button class="text-gray-500 p-2 rounded hover:bg-gray-100">
          <i class="fas fa-microphone"></i>
        </button>
        <button class="text-gray-500 p-2 rounded hover:bg-gray-100 mx-1">
          <i class="fas fa-image"></i>
        </button>
        <button class="text-gray-500 p-2 rounded hover:bg-gray-100 mx-1">
          <i class="fas fa-paperclip"></i>
        </button>
        <button class="text-gray-500 p-2 rounded hover:bg-gray-100">
          <i class="fas fa-folder"></i>
        </button>
      </div>
      
      <div class="flex items-center">
        <textarea 
          placeholder="输入 / 唤起AI助手" 
          class="flex-1 border border-gray-200 rounded-lg p-3 focus:outline-none focus:ring-2 focus:ring-indigo-500 resize-none h-12"
          v-model="newMessage"
          @keydown.enter.prevent="sendMessage"
          @input="autoResizeTextarea"
          ref="messageInput"
          rows="1"
        ></textarea>
        <button 
          class="ml-3 px-5 py-3 bg-indigo-600 text-white rounded-full font-medium hover:bg-indigo-700 focus:outline-none disabled:opacity-50 disabled:cursor-not-allowed"
          @click="sendMessage"
          :disabled="isTyping || !newMessage.trim()"
        >
          发送
        </button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ChatEditor',
  data() {
    return {
      newMessage: '',
      isTyping: false,
      avatars: {
        lkun233: 'https://picsum.photos/id/1012/100/100',
        default: 'https://picsum.photos/id/1005/100/100'
      },
      messages: [
        {
          id: 1,
          type: 'system',
          sender: 'DeepSeekV3',
          collapsible: true,
          collapsed: false,
          content: [
            {
              type: 'paragraph',
              text: '五一国际劳动节源于1886年美国芝加哥工人大罢工，为争取8小时工作制而历尽艰辛。',
              icon: '☀'
            },
            {
              type: 'paragraph',
              text: '1889年第二国际宣布将每年5月1日定为国际劳动节，纪念这次工人运动。',
              icon: '📍'
            },
            {
              type: 'paragraph',
              text: '中国自1949年起正式将5月1日定为法定劳动节，现为小长假（2025年放假4.29-5.3）。',
              icon: '📌'
            },
            {
              type: 'text',
              text: '需要具体历史事件细节可随时咨询我~'
            }
          ],
          time: '前天 15:34',
          meta: '管理员（作者）：五一回来'
        },
        {
          id: 2,
          type: 'user',
          sender: 'lkun233',
          content: '22333',
          time: '今天 15:48'
        },
        {
          id: 3,
          type: 'user',
          sender: 'lkun233',
          content: '2233',
          time: '今天 15:48'
        }
      ],
      currentUser: 'lkun233'
    };
  },
  methods: {
    sendMessage() {
      if (!this.newMessage.trim() || this.isTyping) return;
      
      // Add user message
      this.messages.push({
        id: Date.now(),
        type: 'user',
        sender: this.currentUser,
        content: this.newMessage,
        time: this.formatTime(new Date())
      });
      
      // Clear input and reset height
      const messageCopy = this.newMessage;
      this.newMessage = '';
      this.$nextTick(() => {
        this.$refs.messageInput.style.height = 'auto';
      });
      
      // Set typing indicator
      this.isTyping = true;
      this.scrollToBottom();
      
      // Mock AI response (would be replaced with actual API call)
      setTimeout(() => {
        this.isTyping = false;
        
        this.messages.push({
          id: Date.now(),
          type: 'system',
          sender: 'DeepSeekV3',
          content: `我收到了您的消息: "${messageCopy}"`,
          time: this.formatTime(new Date())
        });
        
        // Scroll to bottom after message is added
        this.$nextTick(() => {
          this.scrollToBottom();
        });
      }, 1500);
    },
    
    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.messageContainer;
        if (container) {
          container.scrollTop = container.scrollHeight;
        }
      });
    },
    
    autoResizeTextarea(event) {
      const textarea = event.target;
      textarea.style.height = 'auto';
      textarea.style.height = Math.min(textarea.scrollHeight, 150) + 'px';
    },
    
    getUserAvatar(username) {
      return this.avatars[username] || this.avatars.default;
    },
    
    getIconClass(icon) {
      if (icon === '☀' || icon === '📍') return 'text-yellow-500';
      if (icon === '📌') return 'text-red-500';
      return 'text-gray-500';
    },
    
    formatTime(date) {
      const now = new Date();
      const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
      const yesterday = new Date(today);
      yesterday.setDate(yesterday.getDate() - 1);
      
      if (date >= today) {
        return `今天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
      } else if (date >= yesterday) {
        return `昨天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
      } else {
        return `${date.getMonth() + 1}月${date.getDate()}日 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
      }
    },
    
    toggleMessageCollapse(messageId) {
      const message = this.messages.find(m => m.id === messageId);
      if (message && message.collapsible) {
        message.collapsed = !message.collapsed;
      }
    }
  },
  mounted() {
    this.scrollToBottom();
  }
};
</script>

<style scoped>
/* Custom styling for the component */
.overflow-y-auto::-webkit-scrollbar {
  width: 6px;
}

.overflow-y-auto::-webkit-scrollbar-track {
  background: transparent;
}

.overflow-y-auto::-webkit-scrollbar-thumb {
  background-color: rgba(0, 0, 0, 0.1);
  border-radius: 3px;
}

textarea {
  min-height: 48px;
  max-height: 150px;
}

.typing-dot {
  width: 8px;
  height: 8px;
  background-color: #6366F1;
  border-radius: 50%;
  animation: typing-animation 1.4s infinite both;
}

.animation-delay-200 {
  animation-delay: 0.2s;
}

.animation-delay-400 {
  animation-delay: 0.4s;
}

@keyframes typing-animation {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-4px);
  }
}
</style>
